<script>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/util/api'

export default {
  name: 'TotalData',
  setup() {
    // 关键指标数据
    const userCount = ref(0)
    const petCount = ref(0)
    const appointmentCount = ref(0)
    const activityCount = ref(0)

    // 图表数据
    const userTrend = ref([])
    const appointmentTrend = ref([])

    // 最新活动列表
    const recentActivities = ref([])

    // 预约状态数据
    const appointmentStatus = ref({
      pending: 0,
      confirmed: 0,
      completed: 0,
      cancelled: 0
    })

    // API调用函数
    const getUsers = async (pageNo = 1, pageSize = 1) => {
      try {
        const response = await api({
          url: '/users',
          method: 'get',
          params: { pageNo, pageSize }
        })
        return response
      } catch (error) {
        console.error('获取用户数据失败:', error)
        throw error
      }
    }

    const getPets = async (pageNo = 1, pageSize = 1) => {
      try {
        const response = await api({
          url: '/pets',
          method: 'get',
          params: { pageNo, pageSize }
        })
        return response
      } catch (error) {
        console.error('获取宠物数据失败:', error)
        throw error
      }
    }

    const getAppointments = async (pageNo = 1, pageSize = 1) => {
      try {
        const response = await api({
          url: '/appointment',
          method: 'get',
          params: { pageNo, pageSize }
        })
        return response
      } catch (error) {
        console.error('获取预约数据失败:', error)
        throw error
      }
    }

    const getActivities = async (pageNo = 1, pageSize = 1) => {
      try {
        const response = await api({
          url: '/activity',
          method: 'get',
          params: { pageNo, pageSize }
        })
        return response
      } catch (error) {
        console.error('获取活动数据失败:', error)
        throw error
      }
    }

    // 加载数据
    const loadData = async () => {
      try {
        // 获取用户数据
        const userResponse = await getUsers(1, 1)
        if (userResponse && userResponse.data && userResponse.data.total) {
          userCount.value = userResponse.data.total
        }

        // 获取宠物数据
        const petResponse = await getPets(1, 1)
        if (petResponse && petResponse.data && petResponse.data.total) {
          petCount.value = petResponse.data.total
        }

        // 获取预约数据
        const appointmentResponse = await getAppointments(1, 1)
        if (appointmentResponse && appointmentResponse.data && appointmentResponse.data.total) {
          appointmentCount.value = appointmentResponse.data.total
        }

        // 获取活动数据
        const activityResponse = await getActivities(1, 1)
        if (activityResponse && activityResponse.data && activityResponse.data.total) {
          activityCount.value = activityResponse.data.total
        }

        // 获取最新活动详情
        const activitiesDetail = await getActivities(1, 5)
        if (activitiesDetail && activitiesDetail.data && activitiesDetail.data.records) {
          recentActivities.value = activitiesDetail.data.records
        }

        // 模拟一些图表数据（实际项目中应从API获取）
        userTrend.value = [
          { month: '1月', count: 120 },
          { month: '2月', count: 132 },
          { month: '3月', count: 101 },
          { month: '4月', count: 134 },
          { month: '5月', count: 90 },
          { month: '6月', count: 230 }
        ]

        appointmentTrend.value = [
          { month: '1月', count: 220 },
          { month: '2月', count: 182 },
          { month: '3月', count: 191 },
          { month: '4月', count: 234 },
          { month: '5月', count: 290 },
          { month: '6月', count: 330 }
        ]

        // 模拟预约状态数据
        appointmentStatus.value = {
          pending: 15,
          confirmed: 42,
          completed: 28,
          cancelled: 5
        }

      } catch (error) {
        ElMessage.error('数据加载失败: ' + (error.message || '未知错误'))
      }
    }

    onMounted(() => {
      loadData()
    })

    return {
      userCount,
      petCount,
      appointmentCount,
      activityCount,
      userTrend,
      appointmentTrend,
      recentActivities,
      appointmentStatus
    }
  }
}
</script>

<template>
  <div class="dashboard-container">
    <h2>数据看板</h2>

    <!-- 关键指标卡片 -->
    <div class="metrics-grid">
      <el-card class="metric-card">
        <div class="metric-content">
          <div class="metric-icon user-icon">
            <i class="el-icon-user"></i>
          </div>
          <div class="metric-info">
            <div class="metric-value">{{ userCount }}</div>
            <div class="metric-label">注册用户</div>
          </div>
        </div>
      </el-card>

      <el-card class="metric-card">
        <div class="metric-content">
          <div class="metric-icon pet-icon">
            <i class="el-icon-star-off"></i>
          </div>
          <div class="metric-info">
            <div class="metric-value">{{ petCount }}</div>
            <div class="metric-label">宠物数量</div>
          </div>
        </div>
      </el-card>

      <el-card class="metric-card">
        <div class="metric-content">
          <div class="metric-icon appointment-icon">
            <i class="el-icon-date"></i>
          </div>
          <div class="metric-info">
            <div class="metric-value">{{ appointmentCount }}</div>
            <div class="metric-label">预约总数</div>
          </div>
        </div>
      </el-card>

      <el-card class="metric-card">
        <div class="metric-content">
          <div class="metric-icon activity-icon">
            <i class="el-icon-tickets"></i>
          </div>
          <div class="metric-info">
            <div class="metric-value">{{ activityCount }}</div>
            <div class="metric-label">活动项目</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card header="用户增长趋势">
            <div class="chart-container">
              <div class="simple-bar-chart">
                <div v-for="item in userTrend" :key="item.month" class="bar-item">
                  <div class="bar-label">{{ item.month }}</div>
                  <div class="bar">
                    <div
                        class="bar-fill"
                        :style="{ height: (item.count / 250 * 100) + '%' }"
                    ></div>
                  </div>
                  <div class="bar-value">{{ item.count }}</div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card header="预约状态分布">
            <div class="chart-container">
              <div class="simple-pie-chart">
                <div class="pie-chart-legends">
                  <div class="legend-item">
                    <span class="legend-color pending"></span>
                    <span>待确认: {{ appointmentStatus.pending }}</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-color confirmed"></span>
                    <span>已确认: {{ appointmentStatus.confirmed }}</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-color completed"></span>
                    <span>已完成: {{ appointmentStatus.completed }}</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-color cancelled"></span>
                    <span>已取消: {{ appointmentStatus.cancelled }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 最新活动列表 -->
    <div class="recent-section">
      <el-card header="最新活动">
        <el-table :data="recentActivities" style="width: 100%" v-loading="recentActivities.length === 0">
          <el-table-column prop="activityName" label="活动名称"></el-table-column>
          <el-table-column prop="maxNum" label="最大参与数" width="120"></el-table-column>
          <el-table-column label="状态" width="100">
            <template #default>
              <el-tag type="success">进行中</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="recentActivities.length === 0" class="empty-table">
          暂无活动数据
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.dashboard-container h2 {
  margin-bottom: 24px;
  color: #303133;
  font-weight: 600;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.metric-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.metric-card:hover {
  transform: translateY(-2px);
  transition: transform 0.3s ease;
}

.metric-content {
  display: flex;
  align-items: center;
  padding: 16px;
}

.metric-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 28px;
  color: white;
}

.user-icon {
  background: linear-gradient(135deg, #409EFF, #337ecc);
}

.pet-icon {
  background: linear-gradient(135deg, #67C23A, #529b2e);
}

.appointment-icon {
  background: linear-gradient(135deg, #E6A23C, #b88230);
}

.activity-icon {
  background: linear-gradient(135deg, #F56C6C, #c45656);
}

.metric-info {
  flex: 1;
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 4px;
  color: #303133;
}

.metric-label {
  color: #909399;
  font-size: 14px;
  font-weight: 500;
}

.charts-section {
  margin-bottom: 24px;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.simple-bar-chart {
  display: flex;
  height: 200px;
  align-items: flex-end;
  gap: 20px;
  width: 100%;
  justify-content: center;
}

.bar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.bar {
  width: 40px;
  height: 150px;
  background-color: #f5f7fa;
  border-radius: 6px;
  position: relative;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

.bar-fill {
  position: absolute;
  bottom: 0;
  width: 100%;
  background: linear-gradient(to top, #409EFF, #79bbff);
  border-radius: 6px;
  transition: height 0.8s ease;
}

.bar-label {
  margin-bottom: 12px;
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.bar-value {
  margin-top: 8px;
  font-size: 12px;
  color: #409EFF;
  font-weight: 600;
}

.simple-pie-chart {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.pie-chart-legends {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  color: #606266;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  display: inline-block;
}

.legend-color.pending {
  background: linear-gradient(135deg, #E6A23C, #f0c78a);
}

.legend-color.confirmed {
  background: linear-gradient(135deg, #67C23A, #a4da89);
}

.legend-color.completed {
  background: linear-gradient(135deg, #409EFF, #8cc5ff);
}

.legend-color.cancelled {
  background: linear-gradient(135deg, #F56C6C, #f8a3a3);
}

.recent-section {
  margin-bottom: 24px;
  overflow: hidden; /* 添加此属性防止容器溢出 */
}

.empty-table {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .metrics-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .metrics-grid {
    grid-template-columns: 1fr;
  }

  .charts-section .el-col {
    margin-bottom: 16px;
  }

  .simple-bar-chart {
    gap: 12px;
  }

  .bar {
    width: 30px;
  }

  /* 优化表格滚动条隐藏 */
  :deep(.el-table__body-wrapper) {
    overflow: hidden !important;
  }

  :deep(.el-table__body) {
    overflow: hidden !important;
  }

  :deep(.el-table) {
    overflow: hidden !important;
  }

  /* 确保表格单元格内容不会导致溢出 */
  :deep(.el-table__cell) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>